package com.woniu.controller;

import com.alibaba.fastjson.JSON;
import com.woniu.entity.Order;
import com.woniu.entity.Product;
import com.woniu.service.IOrderService;
import com.woniu.service.IProductService;
import com.woniu.vo.Constants;
import com.woniu.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@RestController
@Slf4j
public class OrderController {
    @Autowired
    private IOrderService orderService;
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private IProductService iProductService;
    @GetMapping("/orders/{pid}/{number}")
    public ResultVO create(@PathVariable Integer pid, @PathVariable Integer number) throws Exception {

//         productResultVO = restTemplate.getForObject("http://product-service/products/" + pid, ResultVO.class);
        ResultVO productResultVO = iProductService.findByPid(pid);
        Integer status = productResultVO.getStatus();
        if (status == Constants.OPER_FAILURE) {
            return new ResultVO(Constants.OPER_FAILURE, "创建订单失败，未找到商品");
        }

        Map map = (Map) productResultVO.getData();
        Product product = new Product();
        BeanUtils.populate(product, map);
        log.info("查询到 {} 商品，内容：{}", pid, JSON.toJSONString(product));

        try {
            // 创建订单
            Order order = new Order();
            // 为了测试，用户数据就直接定为常量
            order.setUid(1);
            order.setUsername("邓紫棋");
            order.setPid(pid);
            order.setPname(product.getPname());
            order.setPrice(product.getPrice());
            order.setNumber(number);
            orderService.create(order);
            log.info("下单完成，订单信息：{}", JSON.toJSONString(order));

            return new ResultVO(Constants.OPER_SUCCESS, "创建订单成功", order);
        } catch (Exception e) {
            return new ResultVO(Constants.OPER_FAILURE, "创建订单失败", e.getMessage());
        }
    }

    @GetMapping("/orders/pp")
    public ResultVO create() throws Exception {
        return iProductService.testLoadBalance();
    }
}